class Upload {
    // 减少DOM操作
    static Element = (function () {
        // 执行一次，多个对象共享
        let input = document.createElement('input');
        input.type = 'file';
        input.style.display = 'none';
        return input
    }())

    constructor({ url, accept, onSuccess, onError, multiple, headers, data, onConfirm }) {
        this.url = url;
        this.onSuccess = onSuccess || (() => { });
        this.onError = onError || (() => { });
        this.accept = accept || ""
        this.multiple = multiple || false;
        this.headers = Object.assign(headers || {}, { /* 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'  */ })
        this.data = data || {};
        this.onConfirm = onConfirm || (() => { })
        this.init();
    }

    init() {
        Upload.Element.accept = this.accept;
        Upload.Element.multiple = this.multiple;
        Upload.Element.click();
        Upload.Element.onchange = this.onChange.bind(this);
        // 上树 /* 不上树也能实现 */
        // document.body.appendChild(Upload.Element);
    }

    onChange(e) {
        if (!e) {
            return
        }
        let filesList = e.target.files;
        const formdata = new FormData();
        let dataKeys = Object.keys(this.data);
        for (let i in Object.keys(filesList)) {
            formdata.append('file', filesList[i]);
        }
        for (let i in dataKeys) {
            formdata.append(dataKeys[i], this.data[dataKeys[i]]);
        }
        this.onConfirm(formdata);
        this.ajax({
            url: this.url,
            data: formdata
        }).then((res) => {
            this.onSuccessEvent(res)
        }).catch((err) => {
            this.onErrorEvent(err)
        })
    }

    onSuccessEvent(res) {
        this.onSuccess(res);
        this.destory();
    }

    onErrorEvent(res) {
        this.onError(res);
        this.destory();
    }

    destory() {
        // document.body.removeChild(Upload.Element);
    }

    ajax({ url, data }) {
        let ajax = new XMLHttpRequest();
        ajax.open('post', url, true);
        let headerKeys = Object.keys(this.headers);
        // 设置请求头
        for (let i in headerKeys) {
            // 须放在 open方法后面
            ajax.setRequestHeader(headerKeys[i], this.headers[headerKeys[i]])
        }

        ajax.send(data);
        return new Promise((resolve, reject) => {
            // 监听状态码
            ajax.onreadystatechange = function () {
                if (ajax.readyState == 4 && ajax.status == 200) {
                    console.log(ajax.status)
                    // console.log(ajax.response, JSON.parse(ajax.response))
                    let result = JSON.parse(ajax.response)
                    resolve(result)
                }
                else if (ajax.readyState == 4 && ajax.status != 200) {
                    let result = JSON.parse(ajax.response)
                    reject(result)
                }

            }
        })
    }
}

export default Upload